package com.lin.blog.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.blog.entity.Category;
import com.lin.blog.mapper.CategoryMapper;
import com.lin.blog.service.ICategoryService;
import com.lin.constant.ResultCode;
import com.lin.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lin
 * @since 2020-03-08
 */
@Service
@CacheConfig(cacheNames = "category")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    private static final Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;



    /**
     * 获取树状分类列表
     *
     * @return
     */
    @Cacheable(unless = "#result.code!=200")
    @Override
    public Result getTreeCategory() {

        List<Category> parent = new ArrayList<>();

        List<Category> categoryList = categoryMapper.selectList(null);

        // 获取第一层数据 并递归找到子层数据
        for (Category category : categoryList) {
            if (category.getParentId() < 0){
                parent.add(findChildren(category,categoryList));
            }
        }

        return Result.success(parent);
    }

    /**
     * 分类 递归找子元素
     * @param parentCategory
     * @param categoryList
     * @return
     */
    private Category findChildren(Category parentCategory, List<Category> categoryList) {
        for (Category category : categoryList) {
//            logger.info("parentCategory.getId() {}  --  category.getParentId() {} -- {} ",parentCategory.getId(),category.getParentId(),parentCategory.getId() == category.getParentId());
            if (parentCategory.getId().equals(category.getParentId())){

                if (parentCategory.getChildren() == null){
                    parentCategory.setChildren(new ArrayList<Category>());
                }
                parentCategory.getChildren().add(findChildren(category,categoryList));
            }
        }
        return parentCategory;
    }


    /**
     * 通过主键ID查询Category
     *
     * @param id
     * @return
     */
    @Override
    public Result getCategory(Long id) {
        // 参数不为空
        if (id == null) {
            return Result.failure(ResultCode.PARAM_IS_BLANK);
        }

        // 查询
        Category category = categoryMapper.selectById(id);

        // 不存在
        if (category == null) {
            return Result.failure(ResultCode.CATEGORY_NOT_EXIT);
        }

        return Result.success(category);
    }

    /**
     * 插入一条Category记录
     *
     * @param category
     * @return
     */
    @CacheEvict(allEntries = true)
    @Override
    public Result saveCategory(Category category) {

        long id = IdWorker.getId();
        category.setId(id);
        // 当标题为空时 默认设置为一级标题
        if (category.getParentId() == null) {
            category.setParentId(-id);
        }

        // 添加成功 则返回新添数据
        if (categoryMapper.insert(category) > 0) {
            return Result.success(category);
        }
        return Result.failure(ResultCode.INSERT_ERROR);
    }

    /**
     * 通过主键ID删除Category
     *
     * @param id
     * @return
     */
    @CacheEvict(allEntries = true)
    @Override
    public Result removeCategory(Long id) {
        // 参数不为空
        if (id == null) {
            return Result.failure(ResultCode.PARAM_IS_BLANK);
        }
        if (categoryMapper.deleteById(id) > 0) {
            return Result.success();
        }
        return Result.failure(ResultCode.DELETE_ERROR);
    }


    /**
     * 通过主键ID更新Category
     *
     * @param id
     * @param category
     * @return
     */
    @CacheEvict(allEntries = true)
    @Override
    public Result updateCategory(Long id, Category category) {
        // 参数不为空
        if (id == null) {
            return Result.failure(ResultCode.PARAM_IS_BLANK);
        }
        category.setId(id);

        if (categoryMapper.updateById(category) > 0) {
            return Result.success();
        }
        return Result.failure(ResultCode.UPDATE_ERROR);
    }


    /**
     * 获取CategoryList
     *
     * @return
     */
    @Override
    public Result listCategory() {
        return Result.success(categoryMapper.selectList(null));
    }

    /**
     * 分页获取CategoryList
     *
     * @return
     */
    @Cacheable(key = "#pageNum+'/'+#pageSize",unless = "#result.code!=200")
    @Override
    public Result listCategory(Long pageNum, Long pageSize) {
        Page page = new Page(pageNum, pageSize);
        return Result.success(categoryMapper.selectPage(page, null));
    }




}
